/*
 * @Author: zhanghong
 * @Date: 2019-01-17 18:55:01
 * @Description: 所有业务类型的跳转函数
 */
import {
	isApp,
	isAndroid,
	isIOS,
	isIPhone,
	isIPad,
	serialize
} from '@jmfe/jm-common'
import {
	getHomeSchema,
	openNewWebView,
	buildSchema,
	getCouponCenterSchema,
	getSecKillSchema
} from '@jmfe/jm-webview'
import { mSourceQueryString, jdAppGte640, WQ_BIZ } from './constants'
import { removeProtocol } from './imgFormatter'
import { MINIAPP, wxappext, isMiniprogram } from './ENV'

let getItemDetailUrl
let getShopUrl
let getLookSimilarUrl
let getVideoBuyUrl
let getHotWordUrl
function getParam(url, param) {
	var vars = {}
	if (!url) return vars
	url
		.replace(location.hash, '')
		.replace(/[?&]+([^=&]+)=?([^&]*)?/gi, function(m, key, value) {
			vars[key] = value !== undefined ? value : ''
		})

	if (param) {
		return vars[param] ? vars[param] : null
	}
	return vars
}

if (isApp('jd')) {
	getHotWordUrl = function(keyword) {
		return `openapp.jdmobile://virtual?params={"sourceValue":"0_productList_0","des":"productList","keyWord":"${keyword}","from":"search","category":"jump","sourceType":"PCUBE_CHANNEL"}`
	}
	getItemDetailUrl = function(sku) {
		return (
			'openApp.jdMobile://virtual?params={"category":"jump","des":"productDetail","skuId":"' +
			sku +
			'","sourceType":"productDetail","sourceValue":"member"}'
		)
	}

	getShopUrl = function(shopId) {
		return (
			'openApp.jdMobile://virtual?params={"category":"jump","des":"jshopMain","shopId":"' +
			shopId +
			'","sourceType":"mshop" ,"sourceValue":"1111mail","jumpTab":"bigPro"}'
		)
	}

	getLookSimilarUrl = function(skuId) {
		return `openApp.jdMobile://virtual?params={"category":"jump","des":"lookSimilar","sku_id":"${skuId}"}`
	}
} else {
	getHotWordUrl = function(keyword) {
		return `https://so.m.jd.com/ware/search.action?keyword=${keyword}`
	}
	getItemDetailUrl = function(sku, sid) {
		return (
			'//item.m.jd.com/ware/view.action?wareId=' + sku + '&sid=' + (sid || null)
		)
	}

	getShopUrl = function(shopId) {
		return '//shop.m.jd.com/?shopId=' + shopId
	}

	getLookSimilarUrl = function(skuId) {
		return `//home.m.jd.com/myjd/similar/list.action?skuId=${skuId}`
	}
}

if (jdAppGte640 && isApp('jd')) {
	getVideoBuyUrl = function(id) {
		return `openApp.jdMobile://virtual?params={"category":"jump","des":"videoBuy","id":"${id}","testId":"","channel":"","isInstation":"","isHideFloor":""}`
	}
} else {
	getVideoBuyUrl = function(id) {
		return `//h5.m.jd.com/active/faxian/video/index.html?id=${id}`
	}
}

function concatQueryString(url, queryString) {
	url += (/\?/.test(url) ? '&' : '?') + queryString
	return url
}
// 搜索热词跳转
export function toHotWordPage(hotWord) {
	let url = getHotWordUrl(hotWord)
	window.location = url
}

export function toHomePage() {
	if (isApp('jd')) {
		window.location.href = getHomeSchema()
	} else {
		//创建iframe，呼起app schema
		let div = document.createElement('div')
		div.style.visibility = 'hidden'
		div.innerHTML = `<iframe src="${getHomeSchema()}" scrolling="no" width="1" height="1"></iframe>`
		document.body.appendChild(div)

		setTimeout(() => {
			window.location.href = '//m.jd.com'
		}, 1200)
	}
}

export function toUrl(url) {
	if (isApp('jd')) {
		openNewWebView(url)
	} else {
		const schema = buildSchema('virtual', {
			category: 'jump',
			action: 'to',
			des: 'm',
			url: url
		})
		//创建iframe，呼起app schema
		let div = document.createElement('div')
		div.style.visibility = 'hidden'
		div.innerHTML = `<iframe src="${schema}" scrolling="no" width="1" height="1"></iframe>`
		document.body.appendChild(div)

		setTimeout(() => {
			window.location.href = url
		}, 1200)
	}
}

export function jumpAppViaIframe(schema) {
	//创建iframe，呼起app schema
	let div = document.createElement('div')
	div.style.visibility = 'hidden'
	div.innerHTML = `<iframe src='${schema}' scrolling="no" width="1" height="1"></iframe>`
	document.body.appendChild(div)
}

export function toCouponCenterPage() {
	if (isApp('jd')) {
		window.location.href = getCouponCenterSchema()
	} else {
		window.location.href = '//coupon.m.jd.com/center/getCouponCenter.action'
	}
}

function getCouponBuySchema(batchId) {
	return ` openApp.jdMobile://virtual?params={"sourceValue":"0_productList_0","des":"productList","category":"jump","from":"couponBatch","couponId":"${batchId}","tip":"","intel":"22","sourceType":"PCUBE_CHANNEL"}`
}
/**
 * 跳券购页
 * @export
 */
export function toCouponBuyPage(batchId) {
	if (isApp('jd')) {
		window.location.href = getCouponBuySchema(batchId)
	} else {
		window.location.href = `//so.m.jd.com/list/couponSearch.action?couponbatch=${batchId}`
	}
}

export function getAdUrl(link, type) {
	let url
	if (type === '1') {
		url = link
		if (/sale.jd.com\//.test(url)) {
			if (isApp('jd')) url = url.replace(/\/m\//, '/app/')
			else url = url.replace(/\/app\//, '/m/')
		}
	}

	if (type === '2') {
		url = getItemDetailUrl(link)
	}

	if (type === '3') {
		url = getShopUrl(link)
	}
	return url
}

export function getSchemaForNewWebview(url) {
	return (
		'openApp.jdMobile://virtual?params={"category":"jump","des":"getCoupon","action":"to","url":"' +
		encodeURIComponent(url) +
		'"}'
	)
}

//
export function toHTMLPageByUrl(url, useHref) {
	try {
		url = removeProtocol(url)
		if (mSourceQueryString) {
			url = concatQueryString(url, mSourceQueryString)
		}
		if (isApp('jd')) {
			// 如果是pad内
			if (isIPad()) {
				window.location = url
			}
			// 如果是手机jdapp内
			else if (isIOS() && isIPhone()) {
				//用协议打开新webview
				url = 'https:' + url
				if (!useHref) {
					url = getSchemaForNewWebview(url)
				}
				window.location = url
			} else if (isAndroid()) {
				// //安卓里创建a元素,调用模拟点击
				// const atag = $('<a>', {
				//   href: url
				// });
				// atag.trigger('click');
				url = 'https:' + url
				url = getSchemaForNewWebview(url)
				window.location = url
			} else {
				window.location = url
			}
		} else {
			// M
			window.location = url
		}
	} catch (e) {}
}

export function toSeckillChannelUrl(skuId, stageTime) {
	function getSecSchema() {
		if (skuId && stageTime) {
			// return `openApp.jdMobile://virtual?params={"category":"jump","sourceValue":"2017618main","sourceType":"h5","des":"seckill","gid":"","productId":"${skuId}","groupTimes":${stageTime},"m_param":{"jdv":""}}`
			return `openApp.jdMobile://virtual?params={"category":"jump","sourceValue":"2017618main","sourceType":"h5","des":"seckill","productId":"${skuId}","groupTime":${stageTime},"m_param":{"jdv":""}}`
		} else {
			// return 'openApp.jdMobile://virtual?params={\"category\":\"jump\",\"des\":\"seckill\",\"sourceType\":\"" + "h5" + "\" ,\"sourceValue\":\"" + "1111main" + "\"}'
			return getSecKillSchema()
		}
	}
	// ?wareId='+skuId
	const seckillUrl = isApp('jd')
		? getSecSchema()
		: 'https://coupon.m.jd.com/seckill/seckillList'
	window.location.href = seckillUrl
}

/**
 * 充值中心跳转
 */
export function toChargeCenter() {
	try {
		if (isMiniprogram()) {
			go('/pages/recharge/pingou/pingou')
		} else {
			const toUrl = isApp('jd')
				? 'openapp.jdmobile://virtual?params={"category":"jump","des":"jdreactcommon","modulename":"JDReactRechargeModule","appname":"JDReactRechargeModule","ishidden":true,"param":{"page":"home","routeParams":{"source":"newPhonePage"}}}'
				: 'https://newcz.m.jd.com/'

			window.location.href = toUrl
		}
	} catch (error) {
		console.log('charge error', error)
	}
}

export function toAdvertPage(link, linkType, useHref = false) {
	// 跳转200毫秒延时
	// setTimeout(()=>{
	let url = getAdUrl(link, linkType)
	if (linkType === '1') {
		toHTMLPageByUrl(url, useHref)
	}
	//秒杀原生页
	else if (linkType === '10') {
		toSeckillChannelUrl()
	}
	//领圈中心原生页
	else if (linkType == '11') {
		toCouponCenterPage()
	} else {
		//非Murl类型,可能是店铺和商详,app内跳原生
		location = url
	}
	// },200)
}

export function toItemDetailPage(skuId) {
	if (MINIAPP()) {
		wxappext.goto(wxappext.urls.detail + '?sku=' + skuId)
	} else {
		const url = getItemDetailUrl(skuId)
		location = url
	}
}

export function toLogin(jumbBackUrl = location.href) {
	if (isApp('qq') || isApp('wx')) {
		setTimeout(() => {
			window.location.href =
				`https://wq.jd.com/pinbind/pintokenredirect?biz=${WQ_BIZ}&url=` +
				encodeURIComponent(jumbBackUrl)
		}, 100)
	} else {
		const url = 'https://plogin.m.jd.com/user/login.action'
		const params = {
			appid: 100,
			v: 1,
			qqlogin: false,
			wxlogin: false,
			loginonestep: false,
			returnurl: encodeURIComponent(jumbBackUrl)
		}
		setTimeout(() => {
			window.location.href = `${url}?${serialize(params)}`
		}, 100)
	}
}

export function toLookSimilar(skuId) {
	const url = getLookSimilarUrl(skuId)
	location = url
}

export function toVideoBuy(id) {
	const url = getVideoBuyUrl(id)
	// console.log(url)
	location = url
}

export function toNearCoupon(nearbyCouponId, nearbyCouponType, nearbyStoreId) {
	const url = `openapp.jdmobile://virtual?params={"category":"jump","des":"couponCenter","sourceType":"h5","sourceValue":"2018618main","nearbyCouponId":"${nearbyCouponId}","nearbyCouponType":"${nearbyCouponType}","nearbyStoreId":"${nearbyStoreId}","ffp":"1","tab":"5"}`
	location = url
}

/**
 * 跳转结算页
 * @param {*} skuId
 */
export function toOrder(skuId) {
	try {
		if (MINIAPP()) {
			wxappext.goto(`/pages/pay/index/index?sku=${skuId}&num=1&fixednum=1`)
		} else {
			// 跳转H5结算页
			toHTMLPageByUrl(
				`https://wqdeal.jd.com/deal/confirmorder/main?wdref=${encodeURIComponent(
					`https://wqitem.jd.com/item/view?sku=${skuId}`
				)}&commlist=${skuId},,1,${skuId},1,0,0&sceneval=2&fixednum=1`
			)
			// window.location = `https://wqdeal.jd.com/deal/confirmorder/main?wdref=${encodeURIComponent(`https://wqitem.jd.com/item/view?sku=${skuId}`)}&commlist=${skuId},,1,${skuId},1,0,0&sceneval=2&fixednum=1`
		}
	} catch (error) {
		console.log('跳转结算页 error', error)
	}
}

/**
 * 新开webview页面方法：适配微信小程序与JDAPP
 * 默认是H5链接，如果链接格式是以/pages/开头的话，需要标识type为'MINI_PATH'
 * H5 链接必须要以https开头，否则小程序内无法跳转
 * @param {*} url
 */
export function toCommonUrl(url = 'https://m.jd.com', type = 'H5') {
	console.log('redirect url', url, type)
	let urlWithPro = 'https:' + removeProtocol(url)
	try {
		if (MINIAPP()) {
			if (type == 'H5') {
				wxappext.goto(
					`/pages/h5/index?encode_url=${encodeURIComponent(urlWithPro)}`,
					'navigateTo'
				)
			} else {
				go(urlWithPro)
			}
		} else {
			toHTMLPageByUrl(urlWithPro)
		}
	} catch (error) {
		console.log('do task ', error)
	}
}
/**
 * 小程序跳转封装
 */
export function go(path, func = 'navigateTo') {
	try {
		window.wx.miniProgram[func]({
			url: path,
			fail(e) {
				console.error('跳转失败', e, path)
			},
			success(e) {
				console.log(e, '跳转成功', path)
			}
		})
	} catch (error) {
		console.log('error', error)
	}
}
